package com.mhc.haval.controller;

import com.mhc.haval.constant.FuncEnum;
import com.mhc.haval.constant.MsgCodeEnum;
import com.mhc.haval.dal.model.FuncDO;
import com.mhc.haval.dal.query.FuncQuery;
import com.mhc.haval.form.FuncForm;
import com.mhc.haval.form.FuncListQueryForm;
import com.mhc.haval.security.model.User;
import com.mhc.haval.service.FuncService;
import com.mhc.haval.vo.FuncVO;
import com.mhc.suzuki.api.service.IDataDictService;
import com.subaru.common.entity.BizResult;
import com.subaru.common.util.BeanCopierUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author Churry
 * @create 2017-08-23 16:20
 **/
@Slf4j
@RestController
@RequestMapping(value = "/funcs")
public class FuncController {

    @Autowired
    private FuncService funcService;
    @Autowired
    private IDataDictService dataDictService;

    /**
     * 获取功能（权限）列表
     *
     * @return
     */
    @ApiOperation(value = "获取功能（权限）列表", notes = "获取功能列表的数据")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object getFuncList(FuncListQueryForm funcListQueryForm) {
        List<FuncVO> funcList = new ArrayList<>();
        Map<String, Object> queryMap = new HashMap<>(64);
        Optional<FuncListQueryForm> funcListQueryFormOptional = Optional.ofNullable(funcListQueryForm);
        //添加查询条件
        funcListQueryFormOptional.map((queryFrom) -> {
            String keyword = queryFrom.getKeyword();
            queryMap.put("method", queryFrom.getMethod());
            queryMap.put("funcGroupId", queryFrom.getFuncGroupId());
            queryMap.put("isMenu", queryFrom.getIsMenu());
            if (keyword != null && !"null".equals(keyword)) {
                keyword = "%" + keyword + "%";
                queryMap.put("keyword", keyword);
            }
            if (queryFrom.getPageSize() != null && queryFrom.getPageNo() != null) {
                FuncQuery funcQuery = new FuncQuery();
                funcQuery.setPageSize(queryFrom.getPageSize());
                funcQuery.setPageNo(queryFrom.getPageNo());
                queryMap.put("pageSize", queryFrom.getPageSize());
                queryMap.put("pageNo", queryFrom.getPageNo());
                queryMap.put("pageOffset", funcQuery.getPageOffset());
            }
            return queryMap;
        });
        //查询列表
        for (FuncDO funcDO : funcService.getFuncList(queryMap)) {
            FuncVO funcVO = BeanCopierUtil.convert(funcDO, FuncVO.class);
            funcList.add(funcVO);
        }
        BizResult result = BizResult.create(funcList, true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        result.setTotalCount(funcService.countByQueryMap(queryMap));
        //即使前台不带条件，springmvc也会给queryform创建空对象，所以对象判空无效，只能判断属性是否为空
        if (funcListQueryForm.getPageSize() != null) {
            result.setPageSize(funcListQueryForm.getPageSize());
            if (funcListQueryForm.getPageNo() != null) {
                result.setPageNo(funcListQueryForm.getPageNo());
            }
        }
        return result;
    }

    /**
     * 获取功能分组列表
     *
     * @param logedUser
     * @return
     */
    @ApiOperation(value = "获取功能分组列表", notes = "获取功能分组列表")
    @RequestMapping(value = "/group/list", method = RequestMethod.GET)
    public Object getFuncGroupList(@AuthenticationPrincipal User logedUser) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
        try {
            BizResult result = BizResult.create(dataDictService.getGroupDataList(FuncEnum.FUNCGROUP, logedUser.getCompanyNo()), true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
            result.setTotalCount(((List) (result.getData())).size());
            return result;
        } catch (Exception e) {
            log.error("ERROR IN getFuncGroupList", e);
            return BizResult.create(MsgCodeEnum.EXCEPTION.getErrCode(), MsgCodeEnum.EXCEPTION.getErrMsg());
        }
        } else {
            return BizResult.create(MsgCodeEnum.EMPTY_USER.getErrCode(), MsgCodeEnum.EMPTY_USER.getErrMsg());
        }
    }

    /**
     * 新增/修改权限详情
     *
     * @param funcForm
     * @return
     */
    @ApiOperation(value = "新增/修改权限详情", notes = "新增/修改权限详情")
    @ApiImplicitParam(name = "funcForm", value = "权限信息", required = true, paramType = "body", dataType = "funcForm")
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public Object addOrUpdateFunc(@RequestBody FuncForm funcForm) {
        try {
            FuncVO funcVO = BeanCopierUtil.convert(funcForm, FuncVO.class);
            return BizResult.create(funcService.addOrUpdateFunc(funcVO), true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("ERROR IN addOrUpdateFunc", e);
            return BizResult.create(MsgCodeEnum.EXCEPTION.getErrCode(), MsgCodeEnum.EXCEPTION.getErrMsg());
        }
    }

}
